package edu.stanford.prpl.app.prpltalk.android;

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

import android.net.Uri;
import android.util.Log;

/**
 * Represents a IM conversation between a set of participants.
 * It keeps an unique ID, the list of the participants and the list of 
 * already sent messages.
 * Provides functionalities to add messages to the session and to retrieve the session data and to retrieve 
 * a representation of this session's ID as an URI, to be set as Intent data.
 * 
 */
public class ChatSession 
{
	// private final Logger myLogger = Logger.getMyLogger(this.getClass().getName());

	/* List of ids (phone numbers) of all conversation participants */
	private List<String> participantIdList;

	/* The message list */
	private ArrayList<ChatMessage> messageList;

	/* Scheme that shall be used when representing session id as an URI */
	private static final String SESSION_ID_URI_SCHEME = "content";

	/* SSP that shall be used when representing session id as an URI */
	private static final String SESSION_ID_URI_SSP = "sessionId";

	/* Prefix used for building notification title */
	private static final String APP_TITLE = "PrPlTalk - ";
	private static final String NOTIFICATION_TITLE = "Conversation ";

	/* Title that will be shown in chat activity when showing this session's contents */
	private String sessionTitle;

	/* The session id */
	private String sessionId;

    private static final String TAG = "MyActivity";		
	
	
	/**
	 * Instantiates a new conversation session.
	 * 
	 * @param sessionId the session id
	 * @param recvIt iterator on the participant list
	 * @param senderEmail the sender email
	 * @param sessionCounter unique integer assigned to this session 
	 */
	ChatSession(String sessionId, Iterator<String> recvIt, 
			    String senderEmail, int sessionCounter)
	{
		this.sessionId = sessionId;
		this.participantIdList = new ArrayList<String>();
		this.messageList = new ArrayList<ChatMessage>();
		fillParticipantList(recvIt, senderEmail);

		// prepare the session title
		StringBuffer buffer = new StringBuffer(NOTIFICATION_TITLE);
		buffer.append(sessionCounter);
		this.sessionTitle = buffer.toString();
	}

	/**
	 * Instantiates a new conversation session.
	 * 
	 * @param sessionId the session id
	 * @param participantsIds the list of participants' ids
	 * @param sessionCounter unique integer assigned to this session
	 */
	ChatSession(String sessionId, List<String> participantsIds, int sessionCounter) {
		this.sessionId = sessionId;
		this.participantIdList = participantsIds;
		this.messageList = new ArrayList<ChatMessage>();

		// prepare the session title
		StringBuffer buffer = new StringBuffer(APP_TITLE + NOTIFICATION_TITLE);
		buffer.append(sessionCounter);
		this.sessionTitle = buffer.toString();
	}

	/**
	 * Performs a copy of a conversation session.
	 * 
	 * @param session the session to copy
	 */
	ChatSession(ChatSession session) 
	{
		this.sessionTitle = session.sessionTitle;
		this.sessionId = session.sessionId;
		this.messageList = new ArrayList<ChatMessage>();

		for (ChatMessage msg : session.messageList) {
			this.messageList.add(new ChatMessage(msg));
		}

		this.participantIdList 
		= new ArrayList<String>(session.participantIdList);
	}

	/**
	 * Fill the list of participants to this conversation (my contact is not included)
	 * 
	 * @param receiversIt iterator over the list of receivers' email
	 * @param senderPhoneNum the email of the contact that initiates the chat session
	 */
	private void fillParticipantList(Iterator<String> receiversIt, String senderEmail)
	{
		String myEmail = ContactManager.getInstance().getMyContact().getEmail();

		while( receiversIt.hasNext() ) 
		{
			String prplContact = receiversIt.next();

			// AID contactAID = (AID) receiversIt.next();
			// In this application the agent local name is the contact phone number
			// String contactEmail = contactAID.getLocalName();

			// Check that this is not me
			if (!myEmail.equals(prplContact))
			{
				// Add as a new participant
				participantIdList.add(prplContact);
			}
		}

		participantIdList.add(senderEmail);
	}

	/**
	 * Gets the session id as an URI in the form of 
	 * "SESSION_ID_URI_SCHEME://SESSION_ID_URI_SSP#sessionId"
	 * Used for putting the sessionId inside Intent as data.
	 * 
	 * @return the session id as an URI
	 */
	public Uri getSessionIdAsUri()
	{
		return Uri.fromParts(SESSION_ID_URI_SCHEME, SESSION_ID_URI_SSP, 
				             sessionId);
	}

	/**
	 * Overrides Object.equals(). Two sessions are considered equals 
	 * if and only if their session ids are equal
	 * 
	 * @param o object to compare to
	 * @return true if the sessions have same id, false otherwise
	 */
	public boolean equals(Object o) 
	{
		boolean retval = false;
		if (o instanceof ChatSession)
		{
			ChatSession otherSession = (ChatSession) o;
			retval = this.sessionId.equals(otherSession.sessionId);
		}
		return retval;
	}

	/**
	 * Adds the message to this session's message list
	 * @param msg message to be added
	 */
	public void addMessage(ChatMessage msg)
	{		
		messageList.add(msg);
		Log.d(TAG, "Added to chatsessionobj message list the Chat message='"+msg.getMessageContent()+"' by "+msg.getSenderName());
	}

	/**
	 * Gets the message list.
	 * @return the message list
	 */
	public ArrayList<ChatMessage> getMessageList()
	{
		ArrayList<ChatMessage> list = null;
		list = new ArrayList<ChatMessage>(messageList);
		return list;
	}

	public void clearAllMessages()
	{
		if (messageList.isEmpty())
			return;
		messageList.clear();
	}

	/**
	 * Gets the list of participants' ids
	 * @return the participant ids list
	 */
	public List<String> getAllParticipantIds()
	{	
		return participantIdList;
	}

	/**
	 * Gets all participant names.
	 * 
	 * @return the list of all participants' names
	 */
	public List<String> getAllParticipantNames() {
		ArrayList<String> participantNameList = new ArrayList<String>();
		for (String emailId : participantIdList) {
			Contact c = ContactManager.getInstance().getContact(emailId);
			if (c != null) {
				String name = c.getName();
				participantNameList.add(name);
			} else
				participantNameList.add(emailId);
		}
		return participantNameList;
	}

	/**
	 * Gets the participant count.
	 * 
	 * @return the participant count
	 */
	public int getParticipantCount() {
		return participantIdList.size() + 1;
	}

	/**
	 * Gets the session id.
	 * 
	 * @return the session id
	 */
	public String getSessionId() {
		return sessionId;
	}

	/**
	 * Gets the chat session title.
	 * 
	 * @return the session title
	 */
	public String getSessionTitle() {
		return sessionTitle;
	}

	/**
	 * String representation (the session title)
	 * 
	 * @return the session title
	 */
	public String toString() {
		return sessionTitle;
	}

}